var dispatcher = require('../../../util/dispatcher');

module.exports = function(app) {
	return new Handler(app);
};

var Handler = function(app) {
	this.app = app;
};

var handler = Handler.prototype;

/**
 * Gate handler that dispatch user to connectors.
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param {Function} next next stemp callback
 *
 */
handler.queryEntry = function(msg, session, next) {
	var self = this;
	var openid = msg.openid;
	if(!openid) {
		next(null, {
			code: Code.OPENID_INVALID
		});
		return;
	}

	// get all connectors
	var connectors = this.app.getServersByType('connector');
	if(!connectors || connectors.length === 0) {
		next(null, {
			code: Code.SERVER_INVALID
		});
		return;
	}

	self.app.rpc.world.userRemote.auth(session, openid, function(err, uid) {
		if (err || !uid) {
			next(null, {
				code: Code.SYSTEM_ERROR
			});
		} else {
			// select connector
			var res = dispatcher.dispatch(uid, connectors);
			logger.debug("uid=%d openid=%s queryEntry connector=%s", uid, openid, res.id);
			next(null, {
				code: Code.SUCCESS,
				host: res.hostname || res.host,
				port: res.clientPort,
				uid: uid
			});
		}
	});
};

